/******************************************************************************
 *      Mestrado em Ciência da Computação - UFMS
 *		Redes de Computadores - Prof. Dr. Ronaldo Alves Ferreira
 *		Alunos: Geraldo Landre, Marcel Tolentino, Vinícius Bueno
 *****************************************************************************/
/* tmset.c - tmset */

#include "defines.h"
#include "tcptimer.h"
#include "port.h"

/*------------------------------------------------------------------------
 *  tmset -  definir um temporizador rápido
 *------------------------------------------------------------------------
 */
int tmset(int port, int portlen, void *msg, int time)
{
    struct	tqent	*ptq, *newtq, *tq;
    long ctr100 = CLOCKS_PER_SEC/100;
    
    newtq = (struct tqent *)malloc(sizeof(struct tqent));
    newtq->tq_timeleft = time;
    newtq->tq_time = ctr100;
    newtq->tq_port = port;
    newtq->tq_portlen = portlen;
    newtq->tq_msg = msg;
    newtq->tq_next = NULL;

    // clear duplicates
    (void) tmclear(port, msg);

    sem_wait(&tqmutex);
    if (tqhead == NULL) {
        tqhead = newtq;
        thread_resume(timer_thread);
        sem_post(&tqmutex);
        return OK;
    }
    // search the list for our spot

    for (ptq=0, tq=tqhead; tq; tq=tq->tq_next) {
        if (newtq->tq_timeleft < tq->tq_timeleft)
            break;
        newtq->tq_timeleft -= tq->tq_timeleft;
        ptq = tq;
    }
    newtq->tq_next = tq;
    if (ptq)
        ptq->tq_next = newtq;
    else
        tqhead = newtq;
    if (tq)
        tq->tq_timeleft -= newtq->tq_timeleft;
    sem_post(&tqmutex);
    return OK;
}